#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>

#define N 5

static int curid = -1; // 决定哪个线程的myid == curid就输出
static pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

static void *new_thread_job(void *s);

int main(void)
{
    pthread_t tids[N];
    int i;
    int err;

    alarm(5);

    for (i = 0; i < N; i++)
    {
        err = pthread_create(&tids[i], NULL, new_thread_job, (void *)(intptr_t)i);
        if (err)
        {
            fprintf(stderr, "pthread_create(): %s\n", strerror(err));
            exit(1);
        }
    }

    for (;;)
    {
        pthread_mutex_lock(&mut);
        while (curid != -1)
        {
            pthread_cond_wait(&cond, &mut);
        }
        curid = i % N;
        pthread_cond_broadcast(&cond);
        pthread_mutex_unlock(&mut);
        i = (i + 1) % N;
    }

    return 0;
}

static void *new_thread_job(void *s)
{
    int myid = (int)(intptr_t)s;

    while (1)
    {
        pthread_mutex_lock(&mut);
        while (myid != curid)
        {
            pthread_cond_wait(&cond, &mut);
        }
        printf("%c", 'a' + myid);
        fflush(NULL);
        curid = -1;
        pthread_cond_broadcast(&cond);
        pthread_mutex_unlock(&mut);
    }
}

